/**
 * @fileoverview Service Request
 * @description 基于 useFetch 的请求封装（不需要 token）
 */
import { message } from 'ant-design-vue'
import type { UseFetchOptions } from 'nuxt/app'
// 导入API配置
import { proUrl } from './config'

// 响应数据接口
interface ResponseData<T> {
  code: number
  data: T
  message: string
}

// 请求配置选项
interface ServiceRequestOptions<T> extends Omit<UseFetchOptions<ResponseData<T>>, 'baseURL'> {
  // 是否显示错误提示
  showError?: boolean
}

/**
 * 封装 useFetch 请求（不带 token）
 */
export const serviceRequest = <T = any>(url: string, options?: ServiceRequestOptions<T>) => {
  const { showError = true, ...fetchOptions } = options || {}

  // // 使用生产环境URL
  // const baseURL = proUrl.baseUrl

  return useFetch<ResponseData<T>>(url, {
    ...fetchOptions,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      ...(fetchOptions.headers as Record<string, string>),
    } as HeadersInit,
    onRequestError({ error }) {
      // 处理请求错误
      console.error('请求错误:', error)
      if (showError) {
        message.error('请求失败，请检查网络连接')
      }
    },
    onResponse({ response }) {
      // 处理响应数据
      const { code, message: msg } = response._data || {}

      // 业务错误处理
      if (code !== 200 && code !== 0) {
        console.error('业务错误:', msg)
        if (showError) {
          message.error(msg || '请求失败')
        }
      }
    },
    onResponseError({ response }) {
      // 处理响应错误
      const status = response?.status

      if (status) {
        switch (status) {
          case 404:
            console.error('请求资源不存在')
            if (showError) {
              message.error('请求资源不存在')
            }
            break
          case 500:
            console.error('服务器错误')
            if (showError) {
              message.error('服务器错误')
            }
            break
          default:
            console.error(`请求错误: ${status}`)
            if (showError) {
              message.error(`请求错误: ${status}`)
            }
        }
      } else {
        console.error('网络错误')
        if (showError) {
          message.error('网络错误，请检查网络连接')
        }
      }
    },
  })
}

/**
 * GET 请求
 */
export const serviceGet = <T = any>(url: string, options?: ServiceRequestOptions<T>) => {
  return serviceRequest<T>(url, {
    method: 'GET',
    ...options,
  })
}

/**
 * POST 请求
 */
export const servicePost = <T = any>(
  url: string,
  data?: any,
  options?: ServiceRequestOptions<T>,
) => {
  return serviceRequest<T>(url, {
    method: 'POST',
    body: data,
    ...options,
  })
}

/**
 * PUT 请求
 */
export const servicePut = <T = any>(
  url: string,
  data?: any,
  options?: ServiceRequestOptions<T>,
) => {
  return serviceRequest<T>(url, {
    method: 'PUT',
    body: data,
    ...options,
  })
}

/**
 * DELETE 请求
 */
export const serviceDelete = <T = any>(url: string, options?: ServiceRequestOptions<T>) => {
  return serviceRequest<T>(url, {
    method: 'DELETE',
    ...options,
  })
}
